<template>
  <div>
    <el-dialog :title="title" :visible.sync="visible" width="1200px" append-to-body custom-class="import-dialog"
               @close="close"
    >
      <el-form :model="form" :rules="rules" ref="form" label-position="top" label-width="140px" class="add-form">
        <div class="form-section">
          <div class="form-section__title">租住信息</div>
          <div class="form-section__content">
            <el-row :gutter="30">
              <el-col :span="8">
                <el-form-item label="房间" prop="premisesAddress" required>
                  <div slot="label" style="display: inline">
                    <span>房间</span>
                    <el-button
                      size="small"
                      type="primary"
                      icon="el-icon-s-home"
                      @click="dialogSelectRoomVisible = true"
                      style="margin-left: 10px"
                      :disabled="isRelaunch || isSigning || isDesignatedHouse"
                    >选择房间
                    </el-button>
                  </div>

                  <el-input
                    style="width: 100%; margin-left: 10px"
                    v-model="form.premisesAddress"
                    placeholder="请选择房间"
                    readonly
                    :disabled="isRelaunch || isSigning || isDesignatedHouse"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="16">
                <el-form-item label="租住周期" required>
                  <el-row :gutter="30">
                    <el-col :span="7">
                      <el-form-item label="" prop="order.checkInTime">
                        <el-date-picker
                          v-model="form.order.checkInTime"
                          value-format="yyyy-MM-dd HH:ss:mm"
                          align="right"
                          type="date"
                          placeholder="开始日期"
                          :picker-options="startTimeOptions"
                          style="margin-right: 10px;"
                          :disabled="isRelaunch || isSigning"
                          @focus="selectStartEndTime"
                          @change="changeCheckInTime"
                        >
                        </el-date-picker>
                      </el-form-item>
                    </el-col>
                    <el-col :span="7">
                      <el-form-item label="" prop="order.checkOutTime">
                        <el-date-picker
                          v-model="form.order.checkOutTime"
                          value-format="yyyy-MM-dd HH:ss:mm"
                          align="right"
                          type="date"
                          placeholder="结束日期"
                          :picker-options="endTimeOptions"
                          style="margin-right: 10px;"
                          :disabled="isRelaunch || isSigning"
                          @focus="selectStartEndTime"
                          @change="changeCheckOutTime"
                        >
                        </el-date-picker>
                      </el-form-item>
                    </el-col>
                    <el-col :span="10">
                      <el-button-group>
                        <el-button @click="selectTimeType('1')" :disabled="isRelaunch || isSigning">1月</el-button>
                        <el-button @click="selectTimeType('3')" :disabled="isRelaunch || isSigning">3月</el-button>
                        <el-button @click="selectTimeType('6')" :disabled="isRelaunch || isSigning">6月</el-button>
                        <el-button @click="selectTimeType('12')" :disabled="isRelaunch || isSigning">1年</el-button>
                      </el-button-group>
                    </el-col>
                  </el-row>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="30">
              <el-col :span="8">
                <el-form-item label="付款方式" prop="order.rentalMode">
                  <el-radio-group v-model="form.order.rentalMode" @change="changeRentalMode" :disabled="isRelaunch">
                    <el-radio label="1">月付</el-radio>
                    <el-radio label="2">一次性</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="8" v-if="form.order.rentalMode === '1'">
                <el-form-item label="押付方式" prop="order.depositNumber">
                  <el-row>
                    <el-col :span="11">
                      <el-select v-model="form.order.depositNumber" placeholder="请选择押几" :disabled="isRelaunch"
                                 filterable
                      >
                        <el-option :label="item.label" :value="item.value" v-for="item in depositMode"
                                   :key="item.value"
                        ></el-option>
                      </el-select>
                    </el-col>
                    <el-col :span="11">
                      <el-select v-model="form.order.payNumber" placeholder="请选择付几" :disabled="isRelaunch"
                                 filterable
                      >
                        <el-option :label="item.label" :value="item.value" v-for="item in rentalMode" :key="item.value"
                        ></el-option>
                      </el-select>
                    </el-col>
                  </el-row>
                </el-form-item>
              </el-col>
              <el-col :span="8" v-if="form.order.rentalMode === '1'">
                <el-form-item label="月租金(元/月)" prop="order.monthRent">
                  <el-input v-model="form.order.monthRent" placeholder="请输入租金" v-input.float="2"
                            @change="(e)=>form.order.monthRent = Number(e)"
                            :disabled="isRelaunch"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8" v-if="form.order.rentalMode === '2'">
                <el-form-item label="总租金(元)" prop="order.totalRent">
                  <el-input v-model="form.order.totalRent" placeholder="请输入总租金" v-input.float="2"
                            @change="(e)=>form.order.totalRent = Number(e)"
                            :disabled="isRelaunch"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8" v-if="form.order.rentalMode === '2'">
                <el-form-item label="押金(元)" prop="order.deposit">
                  <el-input v-model="form.order.deposit" placeholder="请输入押金" v-input.float="2"
                            @change="(e)=>form.order.deposit = Number(e)"
                            :disabled="isRelaunch"
                  ></el-input>
                </el-form-item>
              </el-col>

            </el-row>
            <el-row :gutter="30" v-if="form.order.rentalMode === '1'">
              <el-col :span="8">
                <el-form-item label="收租日设置" prop="order.rentCollectionDate">
                  <el-row>
                    <el-col :span="10">
                      <el-select v-model="form.order.rentDayType" placeholder="请选择" style="width: 100%"
                                 :disabled="isRelaunch"
                                 filterable
                      >
                        <el-option :label="item.label" :value="item.value" v-for="item in rentDayType"
                                   :key="item.value"
                        ></el-option>
                      </el-select>
                    </el-col>
                    <el-col :span="14">
                      <el-input type="number" v-model.number="form.order.rentCollectionDate" placeholder="请输入收租日"
                                style="width: 100%"
                                :disabled="isRelaunch"
                      >
                        <span slot="append" v-if="form.order.rentDayType === '1'">天收租</span>
                        <span slot="append" v-else>号收租</span>
                      </el-input>
                    </el-col>
                  </el-row>

                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="账单生成时间" prop="order.billGenerationDate">
                  <el-row>
                    <el-col :span="5">
                      收租日前
                    </el-col>
                    <el-col :span="19">
                      <el-input type="number" v-model.number="form.order.billGenerationDate" placeholder="请输入天数"
                                :disabled="isRelaunch"
                      >
                        <span slot="append">天生成</span>
                      </el-input>
                    </el-col>
                  </el-row>

                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="账单生成规则" prop="order.billGenerationType">
                  <el-select v-model="form.order.billGenerationType" placeholder="请选择" style="width: 100%"
                             :disabled="isRelaunch"
                             filterable
                  >
                    <el-option :label="item.label" :value="item.value" v-for="item in billGenerationType"
                               :key="item.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </div>
        <div class="form-section">
          <div class="form-section__title">加收费用</div>
          <div class="form-section__content">
            <el-button @click="addHouseBillItemMerge">添加</el-button>
            <el-table :data="form.houseBillItemMergeList" style="width: 100%">
              <el-table-column label="费用名称" prop="itemName">
                <template #default="scope">
                  <el-select v-model="scope.row.itemName" placeholder="请选择" filterable>
                    <el-option :label="item.label" :value="item.label" v-for="item in billItemList" :key="item.value"
                    ></el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="支付方式" prop="chargeMethod">
                <template #default="scope">
                  <el-select v-model="scope.row.chargeMethod" placeholder="请选择"
                             :disabled="form.order.rentalMode == 2"
                             filterable
                  >
                    <el-option label="一次付清" value="1"></el-option>
                    <el-option label="随租随付" value="2"></el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="金额" prop="itemPrice">
                <template #header>
                  <div><span style="color: red;">*</span><span>金额</span></div>
                </template>
                <template #default="scope">
                  <el-input v-model="scope.row.itemPrice" placeholder="请输入金额" v-input.float="2"
                            @change="(e)=>scope.row.itemPrice = Number(e)"
                  >
                    <span slot="append">元</span>
                  </el-input>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="150">
                <template slot-scope="scope">
                  <el-button size="mini" type="danger" @click="handleDelete(scope.$index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
        <div class="form-section">
          <div class="form-section__title">承租信息</div>
          <div class="form-section__content">
            <el-row :gutter="30" v-show="form.lesseeType === '1'">
              <el-col :span="8">
                <el-form-item label="承租方式" prop="lesseeType">
                  <el-radio-group v-model="form.lesseeType" @change="changeLesseeType">
                    <el-radio label="1">个人</el-radio>
                    <el-radio label="2">企业</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="8" v-if="form.lesseeType === '1'">
                <el-form-item label="联系人姓名" prop="contactName">
                  <el-input v-model="form.contactName" placeholder="请输入联系人姓名"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8" v-if="form.lesseeType === '1'">
                <el-form-item label="联系人手机号" prop="contactPhone">
                  <el-input v-model="form.contactPhone" placeholder="请输入联系人手机号"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8" v-if="form.lesseeType === '1'">
                <el-form-item label="身份证号" prop="cardNumber">
                  <el-input v-model="form.cardNumber" placeholder="请输入身份证号"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="30" v-show="form.lesseeType === '2'">
              <el-col :span="8">
                <el-form-item label="承租方式" prop="lesseeType">
                  <el-radio-group v-model="form.lesseeType" @change="changeLesseeType">
                    <el-radio label="1">个人</el-radio>
                    <el-radio label="2">企业</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="8" v-if="form.lesseeType === '2'">
                <el-form-item label="企业名称" prop="enterpriseName">
                  <el-input v-model="form.enterpriseName" placeholder="请输入企业名称"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8" v-if="form.lesseeType === '2'">
                <el-form-item label="统一社会信用代码" prop="socialCreditCode">
                  <el-input v-model="form.socialCreditCode" placeholder="请输入统一社会信用代码" maxlength="20"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8" v-if="form.lesseeType === '2'">
                <el-form-item label="企业联系人" prop="contactName">
                  <el-input v-model="form.contactName" placeholder="请输入联系人姓名"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8" v-if="form.lesseeType === '2'">
                <el-form-item label="联系人手机号" prop="contactPhone">
                  <el-input v-model="form.contactPhone" placeholder="请输入联系人手机号"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </div>
        <div class="form-section">
          <div class="form-section__title">合约信息</div>
          <div class="form-section__content">
            <el-row :gutter="30">
              <el-col :span="8">
                <el-form-item label="签署方式" prop="signingMode">
                  <el-select v-model="form.signingMode" placeholder="请选择" disabled filterable>
                    <el-option label="平台与租客签约" value="1"></el-option>
                    <el-option label="业主与租客签约" value="2"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="合同分类" prop="contractType" v-if="form.lesseeType === '1'">
                  <el-select v-model="form.contractType" placeholder="请选择" @change="selectContractType" filterable>
                    <el-option :label="dict.label" :value="dict.value"
                               v-for="dict in dict.type.contract_type.filter(item => item.value !== '2')" :key="dict.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="合同分类" prop="contractType" v-if="form.lesseeType=== '2'">
                  <el-select v-model="form.contractType" placeholder="请选择" @change="selectContractType" filterable>
                    <el-option :label="dict.label" :value="dict.value"
                               v-for="dict in dict.type.contract_type.filter(item => item.value === '2')" :key="dict.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="合同模板" prop="contractTemplateId">
                  <el-select v-model="form.contractTemplateId" placeholder="请选择" @change="selectContractTemplate"
                             filterable :disabled="!form.houseId&&form.contractType==='3'"
                  >
                    <el-option :label="item.label" :value="item.value" v-for="item in contractTemplateList"
                               :key="item.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="30">
              <el-col :span="8">
                <el-form-item label="合同编号" prop="contractNumber">
                  <el-input v-model="form.contractNumber" placeholder="请输入合同编号"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="合同扫描件">
                  <el-button @click="dialogUploadContractScanVisible = true"
                             :type="form.contractScanningList.length > 0 ? 'primary' : 'default'"
                             v-text="form.contractScanningList.length > 0 ? '已添加扫描件' : '+添加扫描件'"
                  ></el-button>

                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="补充条款" prop="supplementaryTerms">
                  <el-button @click="dialogSupplementaryTermsVisible = true"
                             :type="form.supplementaryTerms ? 'primary' : 'default'"
                             v-text="form.supplementaryTerms ? '已添加补充条款' : '+ 添加补充条款'"
                  ></el-button>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="30">
              <el-col :span="8">
                <el-form-item label="签约人" prop="busUserId">
                  <el-select v-model="form.busUserId" placeholder="请选择" filterable @change="selectBusUser">
                    <el-option :label="item.label" :value="item.value" v-for="item in houseManagerList"
                               :key="item.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="签约日期" prop="signingTime">
                  <el-date-picker
                    v-model="form.signingTime"
                    value-format="yyyy-MM-dd"
                    align="right"
                    type="date"
                    placeholder="请选择签约日期"
                    :picker-options="latestPaymentDatePickerOption"
                    style="margin-right: 10px;"
                    ref="signingTime"
                  >
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="租客来源" prop="lesseeSourceId">
                  <el-select v-model="form.lesseeSourceId" placeholder="请选择" filterable>
                    <el-option :label="item.label" :value="item.value" v-for="item in lesseeSourceList"
                               :key="item.value"
                    ></el-option>
                  </el-select>

                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="最晚签约日期" prop="latestSigningTime">
                  <el-date-picker
                    v-model="form.latestSigningTime"
                    value-format="yyyy-MM-dd"
                    align="right"
                    type="date"
                    placeholder="请选择最晚签约日期"
                    style="margin-right: 10px;"
                  >
                  </el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </div>
        <div class="form-section">
          <div class="form-section__title">房屋配置</div>
          <div class="form-section__content">
            <el-row :gutter="30">
              <el-col :span="8">
                <el-form-item label="水表读数" prop="waterMeterReading">
                  <el-input type="number" v-model.number="form.waterMeterReading" placeholder="请输入水表读数"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="电表读数" prop="electricityMeterReading">
                  <el-input type="number" v-model.number="form.electricityMeterReading" placeholder="请输入电表读数"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="房屋设施">
                  <el-button @click="dialogAddHousingFacilitiesVisible = true"
                             :type="form.contractFacilitiesItemList.length > 0 ? 'primary' : 'default'"
                             v-text="form.contractFacilitiesItemList.length > 0 ? '已添加房屋设施' : '+添加房屋设施'"
                  ></el-button>

                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="close">取 消</el-button>
        <el-button :loading="loading" type="primary" @click="submitForm" v-text="loading ? '提交中...' : '确 定'">确
          定
        </el-button>
      </div>
    </el-dialog>
    <!-- 选择房间弹窗 -->
    <SelectRoom v-model="dialogSelectRoomVisible" @success="selectRoomSuccessCb" :selected-data="selectedList"/>
    <!-- 上传合同扫描件弹窗 -->
    <UploadContractScan v-model="dialogUploadContractScanVisible" :data.sync="form.contractScanningList"/>
    <!-- 补充条款弹窗 -->
    <SupplementaryTerms v-model="dialogSupplementaryTermsVisible" :data.sync="form.supplementaryTerms"/>
    <!-- 房屋设施弹窗 -->
    <AddHousingFacilities v-model="dialogAddHousingFacilitiesVisible" :data.sync="form.contractFacilitiesItemList"/>
    <!-- 生成账单弹窗 -->
    <GenerateBill v-model="dialogGenerateBillVisible" :data="form" @submit="submitGenerateBillForm"
                  @error="errorGenerateBillForm" @close="closeGenerateBillForm"
    />

  </div>
</template>

<script>
import { houseManagerList } from '@/api/contract/proprietor'
import {
  listBillItem,
  listLesseeSource,
  pageElectronicVisa,
  addLesseeContract,
  relaunchLesseeContract, listRentTime,getTemplateNameByHouse
} from '@/api/contract/lessee'
import { listContractTemplate } from '@/api/contract/template'

import { orderSign } from '@/api/order/order'

import SelectRoom from '@/views/components/select-room/index.vue'
import UploadContractScan from '@/views/long-short-rent/contract/lessee/components/upload-contract-scan.vue'
import SupplementaryTerms from '@/views/long-short-rent/contract/lessee/components/supplementary-terms.vue'
import AddHousingFacilities from '@/views/long-short-rent/contract/lessee/components/add-housing-facilities.vue'
import GenerateBill from '@/views/long-short-rent/contract/lessee/components/generate-bill.vue'

import { debounce } from '@/utils'
import rules from './rules/add'
import { compareDate, isBetween, isOverlap } from '@/utils/common/moment'

export default {
  name: 'add',
  dicts: ['contract_type'],
  components: {
    SelectRoom,
    UploadContractScan,
    SupplementaryTerms,
    AddHousingFacilities,
    GenerateBill
  },
  props: {
    title: {
      default: '新增租客合同'
    },
    value: {
      default: false
    },
    formData: {},
    isRelaunch: {
      type: Boolean,
      default: false
    },
    isSigning: {
      type: Boolean,
      default: false
    },
    //是否指定房屋
    isDesignatedHouse: {
      default: false
    },
    designedHouse: {
      default: ()=>{}
    }, //指定房屋信息
  },
  data() {
    return {
      // visible: false,
      loading: false,
      currentTab: '0',
      //已选择列表
      selectedList: [],
      // 房屋账单加收费用列表
      billItemList: [],
      estateNames: '',
      // 楼层列表
      floorList: [],
      //楼盘列表
      estateList: [],
      //房管家列表
      houseManagerList: [],
      // 租客来源列表
      lesseeSourceList: [],
      // 合同模板列表
      contractTemplateList: [],
      // 选择房间弹窗
      dialogSelectRoomVisible: false,
      // 上传合同扫描件弹窗
      dialogUploadContractScanVisible: false,
      // 补充条款弹窗
      dialogSupplementaryTermsVisible: false,
      // 房屋设施弹窗
      dialogAddHousingFacilitiesVisible: false,
      // 生成账单弹窗
      dialogGenerateBillVisible: false,
      // 房屋甲方人类型
      houseMemberType:"",//
      form: {
        lesseeContractId: '',//合同id
        houseId: '', //房屋id
        orderId: '', //订单id
        premisesAddress: '', //房屋地址
        lesseeType: '1', //承租方式:1.个人;2.企业
        contactName: '', //联系人姓名
        contactPhone: '', //联系人手机号
        cardNumber: '', //身份证号
        enterpriseName: '', //企业名称
        socialCreditCode: '', //社会统一信用代码
        signingMode: '', //签署方式:1.平台与租客签约;2.业主与租客签约
        contractType: '1', //合同类型:1.个人纸质合同;2.企业纸质合同;3.个人电子合同;
        contractTemplateId: '', //合同模板id
        contractTemplateName: '', //模板名称
        contractNumber: '', //合同编号
        contractScanningList: [], //合同扫描件集合
        supplementaryTerms: '', //补充条款
        busUserId: '', //签约人id
        signer: '', //签约人名称
        signingTime: '', //签约时间
        latestSigningTime: '', //最晚签约时间
        lesseeSourceId: '', //来源id
        waterMeterReading: '1666.66', //水表读数
        electricityMeterReading: '6111.11', //电表读数
        order: {},
        contractFacilitiesItemList: [], //房屋设施集合
        houseBillItemMergeList: [] //房屋账单加收费用集合
      },
      // 租期列表
      rentalTimeList: [],
      latestPaymentDatePickerOption: {
        disabledDate(time) {
          return compareDate(time, new Date(), '<')
          // return time.getTime() < Date.now()
        }
      },
      templateType: '',
      // 押金方式
      depositMode: [
        {
          value: 1,
          label: '押一'
        },
        {
          value: 2,
          label: '押二'
        },
        {
          value: 3,
          label: '押三'
        },

        {
          value: 4,
          label: '押四'
        },
        {
          value: 5,
          label: '押五'
        },
        {
          value: 6,
          label: '押六'
        },
        {
          value: 7,
          label: '押七'
        },
        {
          value: 8,
          label: '押八'
        },
        {
          value: 9,
          label: '押九'
        },
        {
          value: 10,
          label: '押十'
        },
        {
          value: 11,
          label: '押十一'
        },
        {
          value: 12,
          label: '押十二'
        }
      ],
      //付租方式
      rentalMode: [
        {
          value: 1,
          label: '付一'
        },
        {
          value: 2,
          label: '付二'
        },
        {
          value: 3,
          label: '付三'
        },
        {
          value: 4,
          label: '付四'
        },
        {
          value: 5,
          label: '付五'
        },
        {
          value: 6,
          label: '付六'
        },
        {
          value: 7,
          label: '付七'
        },
        {
          value: 8,
          label: '付八'
        },
        {
          value: 9,
          label: '付九'
        },
        {
          value: 10,
          label: '付十'
        },
        {
          value: 11,
          label: '付十一'
        },
        {
          value: 12,
          label: '付十二'
        }
      ],
      // 收租日类型
      rentDayType: [
        {
          value: '1',
          label: '每期提前'
        },
        {
          value: '2',
          label: '每期第一个月'
        },
        {
          value: '3',
          label: '每期提前一个月'
        }
      ],
      // 账单生成规则
      billGenerationType: [
        {
          value: '1',
          label: '合同月'
        },
        {
          value: '2',
          label: '自然月'
        }
      ],
      // 开始时间选项
      startTimeOptions: {
        disabledDate: (time) => {
          if (!this.form.houseId) {
            return true
          }
          let arr = this.rentalTimeList.map(item => {
            return isBetween(time, item.startTime, item.endTime)
          })
          if (arr.some(item => item)) {
            return true
          }
          // 禁用大于结束时间
          return this.form.order.checkOutTime && compareDate(time, this.form.order.checkOutTime, '>')
        }
      },
      // 结束时间选项
      endTimeOptions: {
        disabledDate: (time) => {
          if (!this.form.houseId) {
            return true
          }
          let arr = this.rentalTimeList.map(item => {
            return isBetween(time, item.startTime, item.endTime)
          })
          if (arr.some(item => item)) {
            return true
          }
          // 禁用小于入住时间
          return this.form.order.checkInTime && compareDate(time, this.form.order.checkInTime, '<')
        }
      },
      rules: rules.apply(this)
    }
  },
  computed: {
    visible: {
      get() {
        return this.value
      },
      set(val) {
        this.$emit('input', val)
      }
    },
    isDisabled() {
      return false
    }
  },
  watch: {
    value: {
      handler(newVal) {
        if (newVal) {
          this.init()
        }
      },
      immediate: true,
      deep: true
    },
    'form.houseId': {
      handler(newVal) {
        if (newVal) {
          this.getRentalTimeList()
        }
      },
      immediate: true,
      deep: true
    }
  },
  methods: {
    init() {
      //重置
      this.reset()
      //获取房管家列表
      this.getHouseManagerList()
      //获取费用列表
      this.getBillItemList()
      //获取租客来源列表
      this.getLesseeSourceList()
      //合同类型变化
      this.selectContractType()

    },
    //重置表单
    reset() {
      this.form = {
        lesseeContractId: '',//合同id
        houseId: '', //房屋id
        orderId: '', //订单id
        premisesAddress: '', //房屋地址
        lesseeType: '1', //承租方式:1.个人;2.企业
        contactName: '', //联系人姓名
        contactPhone: '', //联系人手机号
        cardNumber: '', //身份证号
        enterpriseName: '', //企业名称
        socialCreditCode: '', //社会统一信用代码
        signingMode: '', //签署方式:1.平台与租客签约;2.业主与租客签约
        contractType: '1', //合同类型:1.个人纸质合同;2.企业纸质合同;3.个人电子合同;
        contractTemplateId: '', //合同模板id
        contractTemplateName: '', //模板名称
        contractNumber: '', //合同编号
        contractScanningList: [], //合同扫描件集合
        supplementaryTerms: '', //补充条款
        busUserId: '', //签约人id
        signer: '', //签约人名称
        signingTime: this.formatDate(new Date(), 'YYYY-MM-DD 00:00:00'),  //签约时间
        latestSigningTime: '', //最晚签约时间
        lesseeSourceId: '', //来源id
        waterMeterReading: '', //水表读数
        electricityMeterReading: '', //电表读数
        order: {
          orderId: '', //订单id
          checkInTime: '', //开始时间
          checkOutTime: '', //结束时间
          rentalMode: '1', //付款方式 :1.月付;2.一次性
          depositNumber: null, //押几
          payNumber: null, //付几
          monthRent: null, //月租金
          rentDayType: '1', //收租日类型:1.每期提前;2.每期第一个月;3.每期提前一个月
          rentCollectionDate: '', //收租日(天/号)
          billGenerationDate: null, //账单生成日期(天)
          billGenerationType: '', //账单生成规则:1.合同月;2.自然月
          deposit: null, //押金
          totalRent: null, //总租金
          orderSource: '3' //订单来源：1订单管理;2嗨小克小程序;3.合同管理(字典字段:order_source)
        },
        contractFacilitiesItemList: [], //房屋设施集合
        houseBillItemMergeList: [], //房屋账单加收费用集合
        houseBillList: [],//入住账单对象
        penaltyStates: '1', //违约金生成状态: 1不收取 2收取
        penaltyScale: null //违约金比例
      }
      if (!this.isSigning && !this.isRelaunch) {
        this.selectedList = []
      }
      //是否重新发起合同
      if (this.isRelaunch) {
        this.form.lesseeContractId = this.formData.lesseeContractId
        this.form.orderId = this.formData.order.orderId
        this.form.houseId = this.formData.houseId
        this.form.premisesAddress = this.formData.order.premisesAddress
        this.form.order.checkInTime = this.formData.order.checkInTime
        this.form.order.checkOutTime = this.formData.order.checkOutTime
        this.form.order.rentalMode = this.formData.order.rentalMode
        this.form.order.depositNumber = this.formData.order.depositNumber
        this.form.order.payNumber = this.formData.order.payNumber
        this.form.order.monthRent = this.formData.order.monthRent
        this.form.order.deposit = this.formData.order.deposit
        this.form.order.totalRent = this.formData.order.totalRent
        this.form.order.rentDayType = this.formData.order.rentDayType
        this.form.order.rentCollectionDate = this.formData.order.rentCollectionDate
        this.form.order.billGenerationDate = this.formData.order.billGenerationDate
        this.form.order.billGenerationType = this.formData.order.billGenerationType
        this.form.signingMode = this.formData.signingMode

      }
      //是否签约
      if (this.isSigning) {
        this.form.houseId = this.formData.houseId
        this.form.premisesAddress = this.formData.premisesAddress
        this.form.order.checkInTime = this.formData.checkInTime
        this.form.order.checkOutTime = this.formData.checkOutTime
        this.form.order.orderId = this.formData.orderId
        this.form.signingMode = this.formData.cooperationType ? this.formData.cooperationType === '1' ? '1' : '2' : ''
      }
      //是否指定房源
      if (this.isDesignatedHouse) {
        this.form.houseId = this.designedHouse.houseId
        this.form.premisesAddress = this.designedHouse.premisesAddress
        this.form.signingMode = this.designedHouse.cooperationType ? this.designedHouse.cooperationType === '1' ? '1' : '2' : ''
      }
      this.getTemplateNameByHouseId(this.form.houseId)
      this.resetForm('form')
    },
    //获取房管家列表
    getHouseManagerList() {
      let params = {
        roleKey: 'houseKeeper'
      }
      houseManagerList(params).then(response => {
        this.houseManagerList = response.data.map(item => {
          return {
            label: item.userName,
            value: item.userId
          }
        })
      })
    },
    //获取费用列表
    getBillItemList() {
      listBillItem().then(response => {
        this.billItemList = response.rows.map(item => {
          return {
            label: item.name,
            value: item.itemId
          }
        })
      })
    },
    //获取租客来源列表
    getLesseeSourceList() {
      listLesseeSource().then(response => {
        this.lesseeSourceList = response.data.map(item => {
          return {
            label: item.lesseeSourceName,
            value: item.lesseeSourceId
          }
        })
      })
    },
    //获取电子合同模板列表
    getElectronicVisaList() {
      let templateName = ''
      // 如果承租人是个人
      if (this.form.lesseeType == '1') {
        templateName = '租客租赁合同_' + this.houseMemberType + '乙方个人'
      } else {
        templateName = '租客租赁合同_' + this.houseMemberType + '乙方企业'
      }
      let params = {
        templateName: templateName,
      }
      console.log('params', params)
      pageElectronicVisa(params).then(response => {
        if(!response.data.signTemplates){
          this.contractTemplateList = []
          return
        }
        this.contractTemplateList = response.data.signTemplates.map(item => {
          return {
            label: item.signTemplateName,
            value: item.signTemplateId
          }
        })
      })
    },

    //选择房间回调
    selectRoomSuccessCb(data) {
      console.log('data', data)
      this.selectedList = data
      this.form.houseId = data[0].houseId
      this.form.premisesAddress = data[0].premisesAddress
      // 根据房屋id获取模板名称前缀
      this.getTemplateNameByHouseId(data[0].houseId)


      //签署方式选择
      if (data[0].cooperationType === '1') {
        this.form.signingMode = '1'
      } else if (data[0].cooperationType === '2') {
        this.form.signingMode = '2'
      }

      //租住周期清空
      this.form.order.checkInTime = ''
      this.form.order.checkOutTime = ''

    },
    getTemplateNameByHouseId(houseId) {
      getTemplateNameByHouse(houseId).then(response => {
        this.houseMemberType = response.msg

        this.selectContractType(this.form.contractType)
      })
    },
    //选择时间类型
    selectTimeType(type) {
      if (!this.form.order.checkInTime) {
        this.$message.error('请选择开始日期')
        return
      }

      // 获取指定时间的月份天数
      let date = this.$moment(this.form.order.checkInTime).add(Number(type), 'M').subtract(1, 'days')
      console.log('date', date, date.format('YYYY-MM-DD'))
      //
      //选择的日期是否与已选择的日期重叠
      let arr = this.rentalTimeList.map(item => {
        return isOverlap(this.form.order.checkInTime, date, item.startTime, item.endTime)
      })
      if (arr.some(item => item)) {
        this.$message.error('选择的日期与已租赁日期重叠')
        return
      }
      //

      this.$set(this.form.order, 'checkOutTime', this.formatDate(date, 'YYYY-MM-DD 00:00:00'))
      this.form.order.checkOutTime = this.formatDate(date, 'YYYY-MM-DD 00:00:00')
    },
    //付款方式改变
    changeRentalMode(val) {
      this.form.houseBillItemMergeList = []
      if (val === '1') {
        this.form.order.deposit = null
        this.form.order.totalRent = null
      } else if (val === '2') {
        this.form.order.depositNumber = null
        this.form.order.payNumber = null
        this.form.order.monthRent = null
        this.form.order.rentCollectionDate = ''
        this.form.order.billGenerationDate = null
      }
      this.form.order.rentalMode = val
    },
    //合同类型改变  1.个人纸质合同;2.企业纸质合同;3.个人电子合同;
    selectContractType(val) {
      console.log('val', val)
      if (val) {
        this.form.contractTemplateId = ''
        this.form.contractTemplateName = ''
      }
      if (this.form.contractType === '3') {
        // 如果未选择房屋，则不显示模板列表
        if (!this.form.houseId) {
          this.contractTemplateList = []
          return
        }
        this.getElectronicVisaList()
      } else {
        let params = {
          contractTemplateName: '',
          templateState: '0',
          templateType: this.form.contractType
        }
        listContractTemplate(params).then(response => {
          this.contractTemplateList = response.data.map(item => {
            return {
              label: item.contractTemplateName,
              value: item.contractTemplateId
            }
          })
        })
      }
    },
    // 承租方式改变
    changeLesseeType() {
      if (this.form.lesseeType == '2') {
        this.form.contractType = '2'
      } else {
        this.form.contractType = '1'
      }
      this.form.contactName = ''
      this.form.contactPhone = ''
      this.form.cardNumber = ''
      this.form.enterpriseName = ''
      this.form.socialCreditCode = ''
      this.form.contactName = ''
      this.form.contactPhone = ''
      console.log('gaibian')

      this.selectContractType(this.form.contractType)
    },
    // 添加房屋加收费用
    addHouseBillItemMerge() {
      this.form.houseBillItemMergeList.push({
        itemName: '', //项目名称
        itemPrice: '', //金额
        chargeMethod: this.form.order.rentalMode == 2 ? '1' : '' //项目收费方式 1一次付清 2随租金付
      })

    },
    // 删除房屋加收费用
    handleDelete(index) {
      this.form.houseBillItemMergeList.splice(index, 1)
    },
    // 选择签约人
    selectBusUser(val) {
      let user = this.houseManagerList.find(item => item.value == val)
      if (user) {
        this.form.signer = user.label
      }

    },
    // 选择合同模板回调
    selectContractTemplate(val) {
      let template = this.contractTemplateList.find(item => item.value == val)
      if (template) {
        this.form.contractTemplateName = template.label
      }
    },
    //签署方式改变
    signingModeChange() {

    },
    // 获取租赁时间列表
    getRentalTimeList() {
      let hosueId = this.form.houseId
      if (!hosueId) return
      listRentTime(hosueId).then(response => {
        this.rentalTimeList = response.data
      })
    },
    selectStartEndTime: debounce(function() {
      if (!this.form.houseId) {
        this.$message.error('请选择房屋')
        return
      }
    }, 1000, true),
    // 选择入住时间
    changeCheckInTime(val) {
      let arr = this.rentalTimeList.map(item => {
        return isOverlap(val, this.form.order.checkOutTime, item.startTime, item.endTime)
      })
      if (arr.some(item => item)) {
        this.$message.error('选择的日期与已租赁日期重叠')
        this.form.order.checkInTime = ''
        return
      }
    },
    // 选择离开时间
    changeCheckOutTime(val) {
      let arr = this.rentalTimeList.map(item => {
        return isOverlap(this.form.order.checkInTime, val, item.startTime, item.endTime)
      })
      if (arr.some(item => item)) {
        this.$message.error('选择的日期与已租赁日期重叠')
        this.form.order.checkOutTime = ''
        return
      }
    },
    //提交表单至生成账单
    submitForm: debounce(function() {
      if (this.form.houseBillItemMergeList.length) {
        for (let i = 0; i < this.form.houseBillItemMergeList.length; i++) {
          if (!this.form.houseBillItemMergeList[i].itemName && !this.form.houseBillItemMergeList[i].itemPrice && !this.form.houseBillItemMergeList[i].chargeMethod) {
            this.$message.error('请完善加收费用信息')
            return
          }
          if (!this.form.houseBillItemMergeList[i].itemName) {
            this.$message.error('请选择费用项目')
            return
          }
          if (!this.form.houseBillItemMergeList[i].itemPrice) {
            this.$message.error('请填写金额')
            return
          }
          if (!this.form.houseBillItemMergeList[i].chargeMethod) {
            this.$message.error('请选择项目支付方式')
            return
          }
        }
      }

      this.$refs['form'].validate((valid) => {
        console.log('valid', valid)
        if (valid) {
          this.dialogGenerateBillVisible = true
          this.loading = true
          // addLesseeContract(this.form).then(res => {
          //   this.$message.success(res.msg)
          //   this.$emit('success')
          //   this.visible = false
          // })
        }
      })
    }, 300, true),
    //生成账单表单提交
    submitGenerateBillForm: debounce(function(form) {
      //是否重新发起合同
      if (this.isRelaunch) {
        relaunchLesseeContract(form).then(res => {
          this.$message.success(res.msg)
          this.$emit('success')
          this.visible = false
          this.loading = false
        }).catch(err => {
          console.log('err', err)
          this.loading = false
        })
      } else if (this.isSigning) {
        orderSign(form).then(res => {
          this.$message.success(res.msg)
          this.$emit('success')
          this.visible = false
          this.loading = false
        }).catch(err => {
          console.log('err', err)
          this.loading = false
        })
      } else {
        addLesseeContract(form).then(res => {
          this.$message.success(res.msg)
          this.$emit('success')
          this.visible = false
          this.loading = false
        }).catch(err => {
          console.log('err', err)
          this.loading = false
        })
      }

    }, 300, true),
    // 生成账单表单错误回调
    errorGenerateBillForm(err) {
      console.log('errorGenerateBillForm', err)
      this.loading = false
    },
    // 关闭生成账单表单回调
    closeGenerateBillForm() {
      this.loading = false
    },
    //关闭
    close() {
      this.reset()
      this.visible = false
    }
  }
}
</script>

<style lang="scss" scoped>
.import-dialog {
  height: auto;
  max-height: 80vh;
  overflow-y: auto;

  .dialog-footer {
    text-align: center;
  }
}

::v-deep .el-dialog__body {
  max-height: 80vh !important;
  overflow-y: auto;
}

.form-section {
  .form-section__title {
    padding: 10px;
    background-color: #F2F2F2;
  }

  .form-section__content {
    padding: 10px;
  }
}

</style>

